package com.wande.dataplatform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wande.common.core.exception.ServiceException;
import com.wande.common.mybatis.core.page.PageQuery;
import com.wande.common.mybatis.core.page.TableDataInfo;
import com.wande.common.satoken.utils.LoginHelper;
import com.wande.dataplatform.common.enums.DataPlatformErrorCode;
import com.wande.dataplatform.domain.DataSource;
import com.wande.dataplatform.domain.EtlInstance;
import com.wande.dataplatform.domain.EtlTask;
import com.wande.dataplatform.domain.dto.EtlTaskDTO;
import com.wande.dataplatform.domain.vo.EtlInstanceVO;
import com.wande.dataplatform.domain.vo.EtlTaskVO;
import com.wande.dataplatform.etl.executor.EtlProgress;
import com.wande.dataplatform.etl.executor.IEtlExecutor;
import com.wande.dataplatform.mapper.DataSourceMapper;
import com.wande.dataplatform.mapper.EtlInstanceMapper;
import com.wande.dataplatform.mapper.EtlTaskMapper;
import com.wande.dataplatform.service.IEtlTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ETL任务服务实现
 *
 * @author dataplatform
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EtlTaskServiceImpl implements IEtlTaskService {

    private final EtlTaskMapper etlTaskMapper;
    private final EtlInstanceMapper etlInstanceMapper;
    private final DataSourceMapper dataSourceMapper;
    private final IEtlExecutor etlExecutor;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTask(EtlTaskDTO dto) {
        // 验证数据源
        validateDataSource(dto.getSourceId());
        validateDataSource(dto.getTargetId());

        EtlTask task = new EtlTask();
        BeanUtil.copyProperties(dto, task);
        task.setTenantId(Long.valueOf(LoginHelper.getTenantId()));
        task.setStatus(1);

        etlTaskMapper.insert(task);
        log.info("创建ETL任务成功: id={}, name={}", task.getId(), task.getName());
        return task.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTask(EtlTaskDTO dto) {
        EtlTask existingTask = etlTaskMapper.selectById(dto.getId());
        if (existingTask == null) {
            throw new ServiceException(DataPlatformErrorCode.ETL_TASK_NOT_FOUND.getMessage());
        }

        // 验证数据源
        if (dto.getSourceId() != null) {
            validateDataSource(dto.getSourceId());
        }
        if (dto.getTargetId() != null) {
            validateDataSource(dto.getTargetId());
        }

        EtlTask task = new EtlTask();
        BeanUtil.copyProperties(dto, task);
        etlTaskMapper.updateById(task);
        
        log.info("更新ETL任务成功: id={}", task.getId());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTask(Long id) {
        EtlTask task = etlTaskMapper.selectById(id);
        if (task == null) {
            throw new ServiceException(DataPlatformErrorCode.ETL_TASK_NOT_FOUND.getMessage());
        }

        etlTaskMapper.deleteById(id);
        log.info("删除ETL任务成功: id={}", id);
        return true;
    }

    @Override
    public EtlTaskVO getTaskById(Long id) {
        EtlTask task = etlTaskMapper.selectById(id);
        if (task == null) {
            throw new ServiceException(DataPlatformErrorCode.ETL_TASK_NOT_FOUND.getMessage());
        }

        EtlTaskVO vo = BeanUtil.copyProperties(task, EtlTaskVO.class);
        
        // 填充数据源名称
        if (task.getSourceId() != null) {
            DataSource source = dataSourceMapper.selectById(task.getSourceId());
            if (source != null) {
                vo.setSourceName(source.getName());
            }
        }
        if (task.getTargetId() != null) {
            DataSource target = dataSourceMapper.selectById(task.getTargetId());
            if (target != null) {
                vo.setTargetName(target.getName());
            }
        }

        return vo;
    }

    @Override
    public TableDataInfo<EtlTaskVO> listTasks(PageQuery pageQuery) {
        LambdaQueryWrapper<EtlTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EtlTask::getTenantId, LoginHelper.getTenantId());
        wrapper.orderByDesc(EtlTask::getCreateTime);

        Page<EtlTaskVO> page = etlTaskMapper.selectVoPage(pageQuery.build(), wrapper);
        
        // 填充数据源名称
        for (EtlTaskVO vo : page.getRecords()) {
            if (vo.getSourceId() != null) {
                DataSource source = dataSourceMapper.selectById(vo.getSourceId());
                if (source != null) {
                    vo.setSourceName(source.getName());
                }
            }
            if (vo.getTargetId() != null) {
                DataSource target = dataSourceMapper.selectById(vo.getTargetId());
                if (target != null) {
                    vo.setTargetName(target.getName());
                }
            }
        }

        return TableDataInfo.build(page);
    }

    @Override
    public Long executeTask(Long id) {
        EtlTask task = etlTaskMapper.selectById(id);
        if (task == null) {
            throw new ServiceException(DataPlatformErrorCode.ETL_TASK_NOT_FOUND.getMessage());
        }

        if (task.getStatus() != 1) {
            throw new ServiceException("任务未启用，无法执行");
        }

        Long instanceId = etlExecutor.execute(task);
        log.info("开始执行ETL任务: taskId={}, instanceId={}", id, instanceId);
        return instanceId;
    }

    @Override
    public Boolean stopTask(Long instanceId) {
        etlExecutor.stop(instanceId);
        log.info("停止ETL任务: instanceId={}", instanceId);
        return true;
    }

    @Override
    public EtlProgress getProgress(Long instanceId) {
        return etlExecutor.getProgress(instanceId);
    }

    @Override
    public TableDataInfo<EtlInstanceVO> listInstances(Long taskId, PageQuery pageQuery) {
        LambdaQueryWrapper<EtlInstance> wrapper = new LambdaQueryWrapper<>();
        if (taskId != null) {
            wrapper.eq(EtlInstance::getTaskId, taskId);
        }
        wrapper.orderByDesc(EtlInstance::getCreateTime);

        Page<EtlInstanceVO> page = etlInstanceMapper.selectVoPage(pageQuery.build(), wrapper);
        
        // 填充任务名称
        for (EtlInstanceVO vo : page.getRecords()) {
            EtlTask task = etlTaskMapper.selectById(vo.getTaskId());
            if (task != null) {
                vo.setTaskName(task.getName());
            }
        }

        return TableDataInfo.build(page);
    }

    /**
     * 验证数据源
     */
    private void validateDataSource(Long datasourceId) {
        DataSource dataSource = dataSourceMapper.selectById(datasourceId);
        if (dataSource == null) {
            throw new ServiceException(DataPlatformErrorCode.DATASOURCE_NOT_FOUND.getMessage());
        }
    }
}
